<template>
	<view class="wrap">
		<view class="write_title">
			<input type="text" v-model="title" placeholder="请输入文章标题" />				
		</view>
		<!-- 内容预览区 -->
		<view class="articleList">
			<template v-for="(item,index) in articleList" :key="index">
				<view class="item" v-if="item.type == 'image'">
					<image :src="item.content" mode="widthFix" :data-index="index" @tap="removeImg"></image>
				</view>
				<view class="item" v-if="item.type == 'text'">
					<textarea placeholder="" v-model="articleList[index].content" />
					<view :data-index="index" class="deleteText" @tap="deleteText">删除</view>
				</view>
			</template>
		</view>
		<!-- 文本内输入区 -->
		<form @submit="submit">
			<view class="inputArea">
				<view class="addImg" @tap="addImg">+图片</view>
				<view class="addText">
					<textarea name="artText" v-model="inputContent" placeholder="请输入文本" />
					<button type="primary" form-type="submit">添加</button>
				</view>
			</view>
		</form>
		<!-- 选择文章分类 -->
		<view class="article_cate">
			<view>文章分类</view>
			<view>
				<picker mode="selector" :range="caties" @change="cateChange">
					<view>{{caties[currentCateIndex]}}</view>
				</picker>
			</view>
		</view>
		<!-- 发布提交按钮 -->
		<view class="submitNow" v-if="articleList.length > 0" @tap="submitNow">发布文章</view>
	</view>
</template>

<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from 'vue';	
	import global from '../../common/global';
	let loginRes;
	const title = ref('');	
	const articleList = ref([]);
	const inputContent = ref('');
	
	//需要上传的图片组和当前上传图片索引
	let needUploadImg = [];
	let uploadIndex = 0;
	
	//分类
	const caties = ref(['点击选择']);
	const currentCateIndex = ref(0);
	//记录后台分类的名称数组
	const catiesFromApi = ref([]);
	//记录客户选择的真实分类id
	const sedCateIndex = ref(0);
		
	//添加图片
	const addImg = ()=>{
		uni.chooseMedia({
			count:1,
			sizeType:['compressed'],
			mediaType:['image'],
			success:(res)=>{
				console.log(res);
				let tempFilePaths = res.tempFiles.map(item=>item.tempFilePath);
				articleList.value.push({'type':'image','content':tempFilePaths[0]})				
			}
		})
	}
	//删除图片
	const removeImg = (e)=>{
		let index = e.currentTarget.dataset.index;
		uni.showModal({
			content:'确定要删除该图片吗',
			title:'提示',
			success: (e) => {
				if(e.confirm){
					articleList.value.splice(index,1);
				}
			}
		})
	}
	//提交文章表单数据
	const submit = (res)=>{
		console.log(res);
		let content = res.detail.value.artText;
		if(content.length < 1){
			uni.showToast({
				title:'请输入内容',
				icon:'none'
			})
			return false;
		}
		articleList.value.push({'type':'text','content':content});
		console.log(articleList.value);
		inputContent.value = ''
	}
	
	//删除文章
	const deleteText = (e)=>{
		console.log(e);
		let index = e.currentTarget.dataset.index;
		uni.showModal({
			content:'你确定删除吗',
			title:'提示',
			success: (e) => {
				if(e.confirm){
					articleList.value.splice(index,1);
				}
			}
		})
		console.log(articleList.value);
	}
	
	//更改分类
	const cateChange = (e)=>{
		console.log(e);
		let sedIndex = e.detail.value;
		currentCateIndex.value = sedIndex;   //客户通过picker选择的索引，但不一定是数据库中真实的id
		//获取选择分类的名称
		if(sedIndex < 0){return false;}
		let cateName = caties.value[sedIndex];
		for(let k in catiesFromApi.value){
			if(cateName == catiesFromApi.value[k]){
				sedCateIndex.value = k;
				break;
			}
		}
		currentCateIndex.value = sedIndex;
	}
	
	
	//发布文章
	const submitNow = ()=>{
		//数据验证
		if(title.value.length < 2){
			uni.showToast({
				title:'请输入标题',
				icon:'none'
			})
			return ;
		}
		if(articleList.value.length < 1){
			uni.showToast({
				title:'请输入文章内容',
				icon:'none'
			})
			return ;
		}
		if(sedCateIndex.value < 1){
			uni.showToast({
				title:'请选择文章分类',
				icon:'none'
			})
			return ;
		}
		for(let i=0;i<articleList.value.length;i++){
			if(articleList.value[i].type == 'image'){
				needUploadImg.push(
					{
						'tmpUrl':articleList.value[i].content,
						'indexID':i,
					}
				);
			}
		}
		console.log(needUploadImg);
		uploadImg();
	}
	const uploadImg = ()=>{
		//如果还没有图片，或者已提交完成，则上传图片
		if(needUploadImg.length < 1 || uploadIndex >= needUploadImg.length ){
			uni.showLoading({
				title:'正在提交'
			})
			uni.request({
				url: global.apiServer + 'art&m=add',
				method: 'POST',
				header: {'content-type' : "application/x-www-form-urlencoded"},
				data: {
					title:title.value,
					content:JSON.stringify(articleList.value),
					uid:loginRes[0],
					random:loginRes[1],
					cate:sedCateIndex.value					
				},
				success: res => {
					if(res.data.status == 'ok'){
						console.log('发布文章后'+res);
						uni.showToast({
							title:'提交成功',
							icon:'none'
						})
						articleList.value		= [];
						currentCateIndex.value	= 0;
						sedCateIndex.value 		= 0;
						needUploadImg			= [];
						title.value				= '';
						setTimeout(()=>{
							uni.switchTab({
								url:'../my/my'
							})
						},1000);						
					}else{
						uni.showToast({
							title:res.data.data,
							icon:'none'
						})
					}
				}
			});
		}else{
			//上传图片
			uni.showLoading({
				title:'上传图片'
			});
			let uploader = uni.uploadFile({
				url			:global.apiServer + 'uploadimg',
				filePath	:needUploadImg[uploadIndex].tmpUrl,
				name		:'file',
				success: (uploadFileRes) => {
					console.log(uploadFileRes);
					uploadFileRes = JSON.parse(uploadFileRes.data);
					if(uploadFileRes.status!='ok'){
						uni.showToast({
							title:'图片上传失败',
							icon:'none'
						})
						return false;
					}
					let index = needUploadImg[uploadIndex].indexID;
					articleList.value[index].content = global.staticServer + uploadFileRes.data;
					uploadIndex++;
					
					setTimeout(()=>{
						uploadImg();
					},1000)
				},
				fail: (e) => {
					console.log(e);
					uni.showToast({
						title:'图片上传失败，请重试',
						icon:'none'
					})
				}
			})
		}
	}
	onLoad(()=>{		
		loginRes = global.checkLogin('../write/write','2');
		if(!loginRes){return false;}
		console.log(loginRes);
		//加载文章分类
		uni.request({
			url: global.apiServer + 'category&m=index',
			method: 'GET',
			success: res => {
				console.log(res);
				if(res.data.status == 'ok'){
					let categories = res.data.data;  //获得的数据形式：{1:'风景',2:'游记',3:'花世界'}
					//picker组件需要的数据形式 ['','','']
					//遍历对象的属性，获取各属性值，追加到数组中caties中
					for(let k in categories){
						caties.value.push(categories[k]);
					}
					
					//记录分类信息
					catiesFromApi.value = caties.value
				}						
			},
			fail: (e) => {
				console.log(e);
			},
			complete: () => {}
		});
	})
</script>

<style lang="scss">
	.wrap{
		
		.write_title{
			padding: 20rpx;
			border-bottom: 2rpx dashed #f1f2f3;
			input{
				width: 100%;
				height: 90rpx;
				line-height: 90rpx;
				font-size: 40rpx;
			}
		}
		.articleList{
			padding: 20rpx;
			.item{
				margin: 20rpx 0;
				overflow: hidden;
				image{
					width: 100% !important;
					height: auto;
				}
				textarea{
					width: 88%;
					margin: 0 auto;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					padding: 10rpx;
					font-size: 28rpx;
					line-height: 1.5em;
					color: #ccc;
					border-bottom: 2rpx solid #d1d2d3;
				}
			}
		}
		.inputArea{
			padding: 20rpx;
			display: flex;
			flex-wrap: nowrap;
			.addImg{
				width: 180rpx;
				height: 180rpx;
				line-height: 180rpx;
				text-align: center;
				font-size: 32rpx;
				background-color: #F4F5F6;
				margin-right: 16rpx;
				flex-shrink: 0;
			}
			.addText{
				width: 100%;
				height: 180rpx;
				display: flex;
				flex-wrap: nowrap;
				background-color: #F4F5F6;
				textarea{
					width: 100%;
					height: 160rpx;
					padding: 20rpx;
					font-size: 28rpx;
				}
				button{
					width:60px; 
					height:90px; 
					font-size:12px; 
					text-align:center; 
					line-height:90px; 
					margin-left:8px; 
					flex-shrink:0;
				}
			}
		}
		.article_cate{
			padding: 20rpx;
			display: flex;
			flex-wrap: nowrap;
			justify-content: space-between;
		}
		.submitNow{
			height: 100rpx;
			line-height: 100rpx;
			font-size: 36prx;
			text-align: center;
			margin: 0 20rpx;
			border-top: 2rpx solid #f1f2f3;
			border-bottom: 2rpx solid #f1f2f3;
		}
	}    
</style>
